from flask import Flask, request, jsonify
from surprise import SVDpp, NormalPredictor

from Evaluator import Evaluator
from flask_utils import LoadData

app = Flask(__name__)

# 全局加载数据和评估器
loader, data, rankings = LoadData()
evaluator = Evaluator(data, rankings)

# 添加算法到评估器
# 奇异值分解
SVDPlusPlus = SVDpp()
evaluator.AddAlgorithm(SVDPlusPlus, "SVD++")


# Random = NormalPredictor()
# evaluator.AddAlgorithm(Random, "Random")


@app.route('/recommend', methods=['GET'])
def recommend():
    """
    推荐接口
    请求参数：
        user_id: 用户ID (int)
        k: 推荐数量 (int, 可选，默认为10)
    返回：
        推荐结果列表，每个元素包含项目ID和预测评分。
    """
    try:
        # 获取请求参数
        # http://127.0.0.1:5000/recommend?user_id=85&k=10
        user_id = int(request.args.get('user_id'))
        k = int(request.args.get('k', 10))  # 默认推荐10个

        # 调用推荐方法
        recommendations = evaluator.SampleTopNRecs(loader=loader, userID=user_id, k=k)

        # 格式化返回结果
        result = [
            {
                "item_id": item_id,
                "item_name": loader.get_name(item_id),
                "estimated_rating": round(rating, 2)
            } for item_id, rating in recommendations
        ]

        return jsonify({"status": "success", "recommendations": result})

    except Exception as e:
        return jsonify({"status": "error", "message": str(e)}), 400


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)
